﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;

public class AppView : MonoBehaviour
{
    public enum EMClientUpdate
    {
        /// <summary>
        /// 新增
        /// </summary>
        Add,
        Del,
        /// <summary>
        /// 删除
        /// </summary>
        none
    }

    EMClientUpdate bNeedUpdateCell = EMClientUpdate.none;
    public GameObject objCell;
    public GameObject objMsgPanel;
    public InputField inputFieldIPConnect;
    public Text txtLocalInfo;
    Dictionary<string, GameObject> dicClient = new Dictionary<string, GameObject>();
    Dictionary<string, GameObject> dicClientMsgPanel = new Dictionary<string, GameObject>();
    Dictionary<string, List<MsgPanel.MsgInfo>> dicClientMsg = new Dictionary<string, List<MsgPanel.MsgInfo>>();
    List<string> vecTipMsgClient = new List<string>();

    public static float fWS = 1f;
    // Start is called before the first frame update
    void Start()
    {
        fWS = GetComponent<RectTransform>().sizeDelta.x;
        objMsgPanel.SetActive(false);
        objCell.SetActive(false);

        string strTemp = "DeviceName: " + SystemInfo.deviceName + "\r\n";
        strTemp += " HostName: " + Dns.GetHostName() + "\r\n";
        strTemp += " IP: ";
        foreach (var it in Dns.GetHostByName(Dns.GetHostName()).AddressList)
        {
            string ip = it.ToString();
            if (ip.Length <= 15)
                strTemp += "[" + ip + "]";
        }
        txtLocalInfo.text = strTemp;

        txtLocalInfo.transform.parent.GetComponent<RectTransform>().sizeDelta = new Vector2(fWS - 20f, objCell.GetComponent<RectTransform>().sizeDelta.y);
        inputFieldIPConnect.transform.parent.GetComponent<RectTransform>().sizeDelta = new Vector2(fWS - 20f, objCell.GetComponent<RectTransform>().sizeDelta.y);

        Broadcast.Instance.Init((EMClientUpdate s) =>
        {// 更新客户数量回调
            bNeedUpdateCell = s;
        }, (MsgPanel.MsgInfo talk, string ip) =>
        {// 客户消息回调
            lock (dicClientMsg)
            {
                if (dicClientMsg.ContainsKey(ip))
                {
                    dicClientMsg[ip].Add(talk);
                }
                else
                {
                    dicClientMsg.Add(ip, new List<MsgPanel.MsgInfo>());
                    dicClientMsg[ip].Add(talk);
                }
            }
            lock (vecTipMsgClient)
            {
                vecTipMsgClient.Add(ip);
            }
        });

        InvokeRepeating("UpdateCell", 0, 2f);
        InvokeRepeating("NewMsgTip", 0, 1f);
    }

    private void OnDestroy()
    {
        Broadcast.Instance.OnDestroy();
    }

    public void SyncClient()
    {
        Broadcast.Instance.SyncClient();
    }

    void NewMsgTip()
    {
        lock (dicClientMsg)
        {
            lock (dicClientMsgPanel)
            {
                foreach (var it in dicClientMsg)
                {
                    if (dicClientMsgPanel.ContainsKey(it.Key))
                    {
                        bool del = false;
                        foreach (var m in it.Value)
                        {
                            if (dicClientMsgPanel[it.Key].activeInHierarchy)
                            {
                                del = true;
                                dicClientMsgPanel[it.Key].GetComponent<MsgPanel>().AddMsg(m);
                                Debug.Log("AppView:: " + m.strMsgTarget.PadRight(18, ' ') + " 需显示消息:[" + m.strMsg + "]");
                            }
                        }
                        if (del)
                        {
                            it.Value.Clear();
                        }
                    }
                }
            }
        }

        lock (vecTipMsgClient)
        {
            if (vecTipMsgClient.Count > 0)
            {
                lock (dicClient)
                {
                    foreach (var it in vecTipMsgClient)
                    {
                        if (dicClient.ContainsKey(it))
                        {
                            dicClient[it].GetComponent<Image>().color = Color.yellow;
                        }
                    }
                }

                vecTipMsgClient.Clear();
            }
        }
    }

    void UpdateCell()
    {
        switch (bNeedUpdateCell)
        {
            case EMClientUpdate.Add:
                lock (Broadcast.dicClient)
                {
                    foreach (var it in Broadcast.dicClient)
                    {
                        lock (dicClient)
                        {
                            if (!dicClient.ContainsKey(it.Key))
                            {
                                var obj = Instantiate(objCell, objCell.transform.parent);
                                obj.SetActive(true);
                                obj.GetComponent<RectTransform>().sizeDelta = new Vector2(fWS - 20f, objCell.GetComponent<RectTransform>().sizeDelta.y);

                                lock (Broadcast.clientInfoSelf)
                                {
                                    if (it.Value.strHostName == Broadcast.clientInfoSelf.strHostName)
                                    {
                                        obj.GetComponentInChildren<Text>().text = "You";
                                    }
                                    else
                                    {
                                        obj.GetComponentInChildren<Text>().text = it.Value.strHostName;
                                    }
                                }

                                obj.GetComponent<CellBT>().Init(it.Key, (string ip) =>
                                {
                                    Debug.Log("AppView:: 点击: " + ip);

                                    lock (Broadcast.clientInfoSelf)
                                    {
                                        if (ip == Broadcast.clientInfoSelf.strIP)
                                        {
                                            return;
                                        }
                                    }

                                    if (dicClientMsgPanel.ContainsKey(ip))
                                    {
                                        dicClientMsgPanel[ip].SetActive(true);
                                    }
                                    else
                                    {
                                        var msgPanel = Instantiate(objMsgPanel, objMsgPanel.transform.parent);
                                        lock (Broadcast.dicClient)
                                        {
                                            msgPanel.GetComponent<MsgPanel>().Init(ip, Broadcast.dicClient[ip].strHostName, (string p) =>
                                          {
                                              lock (dicClient)
                                              {
                                                  dicClient[p].GetComponent<Image>().color = Color.white;
                                              }
                                          });
                                        }
                                        msgPanel.SetActive(true);
                                        msgPanel.GetComponent<RectTransform>().anchoredPosition = objMsgPanel.GetComponent<RectTransform>().anchoredPosition;

                                        dicClientMsgPanel.Add(ip, msgPanel);
                                    }
                                });

                                dicClient.Add(it.Key, obj);

                                // 增加用户同时增加聊天框
                                if (!dicClientMsgPanel.ContainsKey(it.Key))
                                {
                                    var msgPanel = Instantiate(objMsgPanel, objMsgPanel.transform.parent);
                                    msgPanel.GetComponent<MsgPanel>().Init(it.Key, it.Value.strHostName, (string p) =>
                                    {
                                        lock (dicClient)
                                        {
                                            dicClient[p].GetComponent<Image>().color = Color.white;
                                        }
                                    });
                                    msgPanel.SetActive(false);
                                    msgPanel.GetComponent<RectTransform>().anchoredPosition = objMsgPanel.GetComponent<RectTransform>().anchoredPosition;

                                    dicClientMsgPanel.Add(it.Key, msgPanel);
                                }
                            }
                        }
                    }
                }
                break;
            case EMClientUpdate.Del:
                List<string> tempDel = new List<string>();
                lock (Broadcast.dicClient)
                {
                    lock (dicClient)
                    {
                        foreach (var it in dicClient)
                        {
                            if (!Broadcast.dicClient.ContainsKey(it.Key))
                            {
                                tempDel.Add(it.Key);
                            }
                        }

                        foreach (var it in tempDel)
                        {
                            Destroy(dicClient[it]);
                            dicClient.Remove(it);
                        }

                        lock (dicClientMsgPanel)
                        {
                            foreach (var it in tempDel)
                            {
                                if (dicClientMsgPanel.ContainsKey(it))
                                {
                                    Destroy(dicClientMsgPanel[it]);
                                    dicClientMsgPanel.Remove(it);
                                }
                            }
                        }

                        lock (dicClientMsg)
                        {
                            foreach (var it in tempDel)
                            {
                                if (dicClientMsg.ContainsKey(it))
                                {
                                    dicClientMsg.Remove(it);
                                }
                            }
                        }
                    }
                }
                break;
            case EMClientUpdate.none:
            default:
                break;
        }
        bNeedUpdateCell = EMClientUpdate.none;
    }

    public void OnIPConnectClickCB()
    {
        string ip = inputFieldIPConnect.text;
        var arrLength = ip.Split("."[0]);
        if (arrLength.Length < 4)
        {
            return;
        }

        if (dicClientMsgPanel.ContainsKey(ip))
        {
            dicClientMsgPanel[ip].SetActive(true);
        }
        else
        {
            var msgPanel = Instantiate(objMsgPanel, objMsgPanel.transform.parent);
            lock (Broadcast.dicClient)
            {
                msgPanel.GetComponent<MsgPanel>().Init(ip, ip, (string p) =>
                {

                });
            }
            msgPanel.SetActive(true);
            msgPanel.GetComponent<RectTransform>().anchoredPosition = objMsgPanel.GetComponent<RectTransform>().anchoredPosition;

            dicClientMsgPanel.Add(ip, msgPanel);
        }
    }
}
